package com.heima.behavior.service.impl;

import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {

        // 文章ID不能为空  使用注解
        //拿到user对象id
        Integer userId = AppThreadLocalUtils.getUser().getId();
        //2调用查询行为实体方法
        //获取设备ID
        Integer equipmentId = dto.getEquipmentId();
        //根据用户ID和设备ID获取当前     实体行为对象
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, equipmentId);
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);

        if (apReadBehavior == null) {
            //如果查询结果为空，说明是第一次添加 使用存储方法
            ApReadBehavior apReadBehavior1 = new ApReadBehavior();
            apReadBehavior1.setEntryId(apBehaviorEntry.getId());
            apReadBehavior1.setArticleId(dto.getArticleId());
            apReadBehavior1.setCount((short) 1);
            apReadBehavior1.setCreatedTime(new Date());
            apReadBehavior1.setUpdatedTime(new Date());
            ApReadBehavior result = mongoTemplate.save(apReadBehavior1);
            return ResponseResult.okResult(result);
        } else {
            //不为空则使用更新方法
            Short count = apReadBehavior.getCount();
            count++;
            Update update = new Update();
            update.set("updateTime", new Date()).set("count", count);
            UpdateResult result = mongoTemplate.updateMulti(query, update, ApReadBehavior.class);
            return ResponseResult.okResult(result);
        }
    }
}
